<?php
/**
 * 交易市场
 * 
 * Created	: 2011-05-20
 * Modified : 2011-05-21
 * @author  : 陈立强
 */
class Market
{
	public static $cfg = null;
	public static $cfgName = 'build/market';
	
	/**
	 * 游戏开始初始化数据
	 */
	public static function init()
	{
		global $DB, $L, $G;
		$cropList = C('item/crop');
		$fruitList = C('item/fruit');
		$animalList = C('item/animal');
		$gatherList = C('item/gather');
		
		$cfgList = $cropList + $fruitList + $animalList + $gatherList;
		
		
		$DB->beginTransaction();
		
		foreach ($cfgList as $k => $v) {
			// 动物配置,市场只卖产品数据
			if ($v['item_type'] == 5) {
				$item_id = $v['product_id'];
				$item_type = $v['product_item_type'];
				$item_title = $v['product_title'];
			} else {
				$item_id = $k;
				$item_type = $v['item_type'];
				$item_title = $v['title'];
			}
			for ($i=1; $i<=3; $i++) {
				$sql = 'SELECT mk_id FROM market WHERE item_id='.$item_id.' AND quality='.$i;
				$exists = $DB->getValue($sql);
				$data = array(
					'item_id'	=> $item_id,
					'item_title'=> $item_title,
					'item_type'	=> $item_type,
					'skill_id'	=> $v['skill_id'],
					'quality'	=> $i,
					'num'		=> 0
				);
				if (!$exists) {
					$DB->insert('market', $data);
				}
			}
		}
		
		$DB->commit();
		
		return true;
	}
	
	/**
	 * 出售原材料
	 * @param int $uid
	 * @param int $depot_id
	 * @param int $num 出售数量
	 * @param int $price 出售价
	 */
	public static function sale($uid, $depot_id, $num, $price)
	{
		global $DB, $L, $G, $m;
		
		$depot_id = (int)$depot_id;
		$num = (int)$num;
		
		$sql = 'SELECT * FROM depot WHERE depot_id='.$depot_id;
		$depotInfo = $DB->getValue($sql);
		if (!$depotInfo) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		// 不是自己的物品不能出售
		if ($depotInfo['uid'] != $uid) {
			return array(
				'val' => false,
				'msg' => $L['Invalid_uid']
			);
		}
		// 出售的数量大于库存
		if ($depotInfo['num'] < $num) {
			return array(
				'val' => false,
				'msg' => $L['sale_item_not_enough']
			);
		}
		
		
		// 玩家出售批次超出限制(货架不足)
		$cnt = $DB->getCount('market_user_sale', 'uid='.$uid);
		$shelfCnt = $DB->getCount('market_user_shelf', 'uid='.$uid);
		if ($cnt >= ($G['market_max_sale_group'] + $shelfCnt)) {
			return array(
				'val' => false,
				'msg' => $L['user_sale_group_is_full']
			);
		}
		
		$item_id = $depotInfo['item_id'];
		$quality = $depotInfo['quality'];
		
		$cfgList = C('item/item_list');
		$cfg = $cfgList[$item_id];
		$maxPrice = $cfg['price'][$quality] * $G['market_sale_price_max'];
		// 出售价格超出上限
		if ($price > $maxPrice) {
			return array(
				'val' => false,
				'msg' => sprintf($L['market_sale_price_too_dear'], $maxPrice)
			);
		}
		// 出售价格超出下限
		if ($price < $cfg['price'][$quality]) {
			return array(
				'val' => false,
				'msg' => sprintf($L['market_sale_price_too_cheap'], $cfg['price'][$quality])
			);
		}
		
		// 仓库的对应物品信息
		$sql = 'SELECT * FROM market WHERE item_id='.$item_id.' AND quality='.$quality;
		$record = $DB->getValue($sql);
		
		$DB->beginTransaction();
		$ret = true;
		
		$newNum = $record['num'] + $num;
		if ($record['min_price'] == 0 || $record['min_price'] > $price) {
			$minPrice = ',min_price='.$price;
			// 缓存最低价
			$m->set('marketMinPrice-'.$item_id.'_'.$quality, $price);
		} else {
			$minPrice = '';
		}
		$sql = 'UPDATE market SET num=num+'.(int)$num.$minPrice.' WHERE mk_id='.$record['mk_id'];
		$ret = $DB->exeSql($sql);
		
		// 用户出售记录
		if ($ret) {
			$now = time();
			$endTime = $now + 86400;
			$sql = 'SELECT mk_id FROM market WHERE item_id='.$item_id.' AND quality='.$quality;
			$mk_id = $DB->getValue($sql);
			$data = array(
				'uid'		=> $uid,
				'mk_id'		=> $mk_id,
				'item_id'	=> $item_id,
				'nickname'	=> $_SESSION['nickname'],
				'quality'	=> $quality,
				'num'		=> $num,
				'price'		=> $price,
				'sale_time'	=> $now,
				'end_time'	=> $endTime,//24小时后结束
			);
			$ret = $DB->insert('market_user_sale', $data);
		}
		
		// 记录用户最早的出售结束时间
		if ($ret) {
			$sql = 'SELECT sale_end_time FROM user WHERE uid='.$uid;
			$saleEndTime = $DB->getValue($sql);
			if ($saleEndTime == 0) {
				$sql = 'UPDATE user SET sale_end_time='.$endTime.' WHERE uid='.$uid;
				$ret = $DB->exeSql($sql);
			}
		}
		
		// 仓库物品减少一定的数量
		if ($ret) {
			$sql = 'UPDATE depot SET num=num-'.(int)$num.' WHERE depot_id='.$depot_id;
			$ret = $DB->exeSql($sql);
		}
		
		// 得到交换券
		if ($ret) {
			$quality = $depotInfo['quality'];
			$getExCoupon = $cfg['lvl'] * $G['market_sale_exchange_coupon'][$quality] * $num;
			
			$exCoupon = $DB->getValue('SELECT exchange_coupon FROM user WHERE uid='.$uid);
			if ($exCoupon == $G['market_max_ex_coupon']) {
				$getExCoupon = 0;
				$ret = true;
			} elseif (($exCoupon+$getExCoupon) > $G['market_max_ex_coupon']) {
				$getExCoupon = $G['market_max_ex_coupon'] - $exCoupon;
				$sql = 'UPDATE user set exchange_coupon='.$G['market_max_ex_coupon'].' WHERE uid='.$uid;
				$ret = $DB->exeSql($sql);
				if ($ret !== false) {
					$ret = true;
				}
			} else {
				$sql = 'UPDATE user set exchange_coupon=exchange_coupon+'.$getExCoupon.' WHERE uid='.$uid;
				$ret = $DB->exeSql($sql);
				if ($ret !== false) {
					$ret = true;
				}
			}
		}
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
//				'get_coin' => $getCoin,
				'get_excoupon' => $getExCoupon,
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('market_sale', $str);
		}

		return $result;
	}
	
	/**
	 * 从市场(黑市)购买材料 
	 * @param int $uid
	 * @param int $mk_id 集市的物品ID
	 * @param int $num 购买数量
	 * @param int $fromBlack 购买数量
	 */
	public static function buy($uid, $mk_id, $num)
	{
		global $DB, $L, $G;
		
		$mk_id = (int)$mk_id;
		$num = (int)$num;
		
		$sql = 'SELECT * FROM market WHERE mk_id='.(int)$mk_id;
		$record = $DB->getValue($sql);
		
		$sql = 'SELECT coin,exchange_coupon FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);
		
		$item_id = $record['item_id'];
		$quality = $record['quality'];
		$cfgList = C('item/item_list');
		$cfg = $cfgList[$item_id];
		// 黑市价格高出正常价格(配置倍率)
		$coin = round($cfg['price'][$quality] * $num) * $G['black_market_sale_rate'];
		$exCoupon = $cfg['lvl'] * $G['market_buy_exchange_coupon'][$quality] * $num;
		
		// 金钱不足
		if ($user['coin'] < $coin) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		
		// 交换券不足
		if ($user['exchange_coupon'] < $exCoupon) {
			return array(
				'val' => false,
				'msg' => $L['exchange_coupon_not_enough']
			);
		}
		
		$DB->beginTransaction();
		
		// 扣除金钱和交换券
		$sql = 'UPDATE user set coin=coin-'.$coin
				.',exchange_coupon=exchange_coupon-'.$exCoupon.' WHERE uid='.$uid;
		$ret = $DB->exeSql($sql);
		if ($ret!==false) $ret = true;
		
		// 物品入库
		if ($ret) {
			$data = array(
				'item_id'	=> $item_id,
				'item_type'	=> $cfg['type'],
				'title'		=> $cfg['title'],
				'num'		=> $num,
				'lvl'		=> $cfg['lvl'] ,
				'stack'		=> 1,
				'quality'	=> $quality,
			);
			$ret = Depot::in($uid, $data);
			if ($ret['val']) {
				$depot_id = $ret['data']['depot_id'];
			} else {
				$msg = $ret['msg'];
			}
			$ret = (bool)$ret['val'];
		}
	
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'used_coin' => $coin,
				'used_exchange_coupon' => $exCoupon,
			);
		} else {
			$DB->rollBack();
			if (isset($msg)) {
				$result['msg'] = $msg;
			} else {
				$result['msg'] = $L['Failure_Update'];
			}
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('market_buy', $str);
		}
		
		return $result;
	}
	
	/**
	 * 从市场(玩家)购买材料 
	 * @param int $uid
	 * @param int $mus_id 集市的玩家出售物品ID
	 * @param int $num 购买数量
	 */
	public static function buyFromUser($uid, $mus_id, $num)
	{
		global $DB, $L, $G;
		
		$mus_id = (int)$mus_id;
		$num = (int)$num;
		$now = time();
		
		$sql = 'SELECT * FROM market_user_sale WHERE id='.(int)$mus_id;
		$record = $DB->getValue($sql);
		// 数量不足
		if ($num > $record['num']) {
			return array(
				'val' => false,
				'msg' => $L['market_item_num_not_enough']
			);
		}
		// 销售记录已经过期了
		if ($record['end_time'] <= $now) {
			return array(
				'val' => false,
				'msg' => $L['market_sale_is_ended']
			);
		}
		if ($record['uid'] == $uid) {
			return array(
				'val' => false,
				'msg' => $L['market_cannot_buy_self_item']
			);
		}
		
		$sql = 'SELECT coin,exchange_coupon FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);
		
		$item_id = $record['item_id'];
		$quality = $record['quality'];
		$cfgList = C('item/item_list');
		$cfg = $cfgList[$item_id];
		// 黑市价格高出正常价格(配置倍率)
		$coin = round($record['price'] * $num);
		$exCoupon = $cfg['lvl'] * $G['market_buy_exchange_coupon'][$quality] * $num;
		
		// 金钱不足
		if ($user['coin'] < $coin) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		
		// 交换券不足
		if ($user['exchange_coupon'] < $exCoupon) {
			return array(
				'val' => false,
				'msg' => $L['exchange_coupon_not_enough']
			);
		}
		
		$DB->beginTransaction();
		
		// 集市数量减少
		if ($record['num'] > 0) {
			$sql = 'UPDATE market SET num=num-'.$num.' WHERE item_id='.$item_id.' AND quality='.$quality;
			$ret = $DB->exeSql($sql);
			if ($ret!==false) $ret = true;
		} else {
			$ret = true;
		}
		// 玩家销售记录相应减少或删除
		if ($ret && $record['num'] > $num) {
			$sql = 'UPDATE market_user_sale SET num=num-'.$num.' WHERE id='.$mus_id;
			$ret = $DB->exeSql($sql);
			if ($ret!==false) $ret = true;
		} else if ($ret) {
			$sql = 'DELETE FROM market_user_sale WHERE id='.$mus_id;
			$ret = $DB->exeSql($sql);
			if ($ret!==false) $ret = true;
			// 判断玩家的最早结束的销售记录时间
			// 卖方数据
			$sql = 'SELECT nickname,sale_end_time FROM user WHERE uid='.$record['uid'];
			$seller = $DB->getValue($sql);
			if ($seller['sale_end_time'] == $record['end_time']) {
				$sql = 'SELECT min(end_time) FROM market_user_sale WHERE uid='.$uid;
				$newEndTime = (int)$DB->getValue($sql);
			}
		}
		
		// 扣除金钱和交换券
		if ($ret) {
			if (isset($newEndTime)) {
				$setStr = ',sale_end_time='.$newEndTime;
			} else {
				$setStr = '';
			}
			$sql = 'UPDATE user set coin=coin-'.$coin
					.',exchange_coupon=exchange_coupon-'.$exCoupon.$setStr.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
			if ($ret!==false) $ret = true;
		}
		
		// 物品入库
		if ($ret) {
			$data = array(
				'item_id'	=> $item_id,
				'item_type'	=> $cfg['type'],
				'title'		=> $cfg['title'],
				'num'		=> $num,
				'lvl'		=> $cfg['lvl'] ,
				'stack'		=> 1,
				'quality'	=> $quality,
			);
			$ret = Depot::in($uid, $data);
			if (!$ret['val']) {
				$msg = $ret['msg'];
			} else {
				$msg = $L['Failure_Update'];
			}
			$ret = (bool)$ret['val'];
		}
		
		// 发送邮件通知
		if ($ret) {
			$DB->setTransactionState(false);
			$mailContent = sprintf(
									$L['market_sale_mail_msg'], 
									$_SESSION['nickname'],
									$cfg['title'],
									$num,
									$coin
							);
			$ret = Mail::send($uid, $record['nickname'], $mailContent, 1);
			$DB->setTransactionState(true);
		}
	
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'used_coin' => $coin,
				'used_exchange_coupon' => $exCoupon,
			);
		} else {
			$DB->rollBack();
			if (isset($msg)) {
				$result['msg'] = $msg;
			} else {
				$result['msg'] = $L['Failure_Update'];
			}
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('market_buy_from_user', $str);
		}
		
		return $result;
	}
	
	/**
	 * 获取市场列表
	 * @param int $uid
	 * @param int|string $type 物品类型
	 * @param int|string $skill_id 物品技能类型ID
	 * @param string $title 物品标题
	 * @param int $quality 物品品质ID
	 * @param int $pageNo 当前显示第几页
	 * @param int $pageSize 每页显示多少条记录,默认30条
	 */
	public static function getList($uid, $type, $skill_id=null, $title='', $quality=0, $pageNo=1)
	{
		global $DB, $L, $G;
		
		$quality = (int)$quality;
		$pageNo = $pageNo==0 ? 1 : $pageNo;
		$pageSize = $G['market_list_page_size'];
		
		$where = '';
		if (is_int_string($type) && $type>0) {
			$where .= ' item_type='.(int)$type;
		} elseif (preg_match('~^(?:[\d]+\,)+[\d]+$~is', $type)) {
			$where .= ' item_type in ('.$type.')';
		} elseif (!empty($title)) {
			$itemNameList = C('item/item_name_id_list');
			$where .= ' item_title = \'%'.$title.'%\'';
			if ($quality) {
				$where .= ' AND quality='.$quality;
			}
		} elseif (!is_null($skill_id)) {
			$where .= ' skill_id='.(int)$skill_id;
		}
		if ($where == '') {
			$sql = 'SELECT * FROM market';
		} else {
			$sql = 'SELECT * FROM market WHERE '.$where;
		}
		if ($pageNo > 0) {
			$total = $DB->getCount('market', $where);
			$pageNum = ceil($total/$pageSize);
			if ($pageNo > $pageNum) {
				$pageNo = $pageNum;
			}
			$start = ($pageNo-1)*$pageSize;
			$sql .= ' limit '.$start.', '.$pageSize;
			$data['total_num'] = $total;
			$data['cur_page'] = $pageNo;
			$data['max_page'] = $pageNum;
		}
		$marketList = $DB->getList($sql);
		
		$cfgList = C('item/item_list');
		
		$list = array();
		$itemIdList = array();
		foreach ($marketList as $k => $v) {
			$itemIdList[] = $v['item_id'];
			$cfg = $cfgList[$v['item_id']];
			$num = $v['num'];
			if ($num==0) {
				$price = $cfg['price'][$v['quality']] * $G['black_market_sale_rate'];
			} else {
				$price = $v['min_price'];
			}
			$list[] = array(
				'mk_id'		=> $v['mk_id'],
				'item_id'	=> $v['item_id'],
				'item_type'	=> $v['item_type'],
				'title'		=> $cfg['title'],
				'min_price'	=> $price,
				'base_price'=> $cfg['price'][$v['quality']],
				'num'		=> $num,
				'lvl'		=> $cfg['lvl'],
				'quality'	=> $v['quality']
			);
		}
		
		$sql = 'SELECT depot_id,item_id,num,quality FROM depot WHERE uid='.$uid
				.' AND item_id IN ('.join(',', $itemIdList).')';
		$depotItemList = $DB->getList($sql);
		$holdList = array();
		$depotIdList = array();
		foreach ($depotItemList as $v) {
			$key = $v['item_id'].','.$v['quality'];
			$holdList[$key] = $v['num'];
			$depotIdList[$key] = $v['depot_id'];
		}
		
		foreach ($list as $k=>$v) {
			$key = $v['item_id'].','.$v['quality'];
			if (isset($holdList[$key])) {
				$list[$k]['hold_num'] = $holdList[$key];
				$list[$k]['depot_id'] = $depotIdList[$key];
			} else {
				$list[$k]['hold_num'] = 0;
				$list[$k]['depot_id'] = 0;
			}
		}
		$data['list'] = $list;
		
		return array(
			'val' => true,
			'data' => $data
		);
	}
	
	/**
	 * 获取所有物品类别名称列表
	 * @param int $uid 用户ID,用户接口请求默认当前登录用户
	 */
	public static function getItemTypeList($uid)
	{
		$list = C('item/item_type_name_market');
		
		return array(
			'val'  => true,
			'data' => $list
		);
	}
	
	/**
	 * 修改出售价格
	 * @param int $uid
	 * @param int $sale_id 出售的ID
	 */
	public static function changePrice($uid, $sale_id, $price)
	{
		global $DB, $L, $G;
		
		$sql = 'SELECT * FROM market_user_sale WHERE id='.$sale_id;
		$record = $DB->getValue($sql);
		if ($record['uid'] != $uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		$record['price'] = $price;
		
		$data = array(
			'price' => (int)$price
		);
		$ret = $DB->update('market_user_sale', $data, 'id='.$sale_id);
		
		return array(
			'val'	=> true,
			'data'	=> $record
		);
	}
	
	/**
	 * 抛售
	 * @param int $uid
	 * @param int $sale_id
	 */
	public static function undersell($uid, $sale_id) 
	{
		global $DB, $L, $G;
		
		$sale_id = (int)$sale_id;
		
		$sql = 'SELECT * FROM market_user_sale WHERE id='.$sale_id;
		$record = $DB->getValue($sql);
		if ($record['uid'] != $uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$quality = $record['quality'];
		$cfgList = C('item/item_list');
		$cfg = $cfgList[$record['item_id']];
		$getCoin = round($record['num'] * ($cfg['price'][$quality] * $G['undersell_price_param']));
		
		$DB->beginTransaction();
		
		// 判断玩家的最早结束的销售记录时间
		$sql = 'SELECT sale_end_time FROM user WHERE uid='.$uid;
		$saleEndTime = $DB->getValue($sql);
		if ($saleEndTime == $record['end_time']) {
			$sql = 'SELECT min(end_time) FROM market_user_sale WHERE uid='.$uid;
			$newEndTime = (int)$DB->getValue($sql);
			$newSqlStr = ',sale_end_time='.$newEndTime;
		} else {
			$newSqlStr = '';
		}
		
		// 得到金钱
		$sql = 'UPDATE user SET coin=coin+'.$getCoin.$newSqlStr.' WHERE uid='.$uid;
		$ret = $DB->exeSql($sql);
		if ($ret !== false ) $ret = true;
		
		// 市场上的对应物品的数量和最低价要更新
		if ($ret) {
			$sql = 'SELECT MIN(price) FROM market_user_sale WHERE mk_id='.$record['mk_id'];
			$min_price = $DB->getValue($sql);
			$sql = 'UPDATE market SET num=num-'.$record['num'].',min_price='.$min_price.' WHERE mk_id='.$record['mk_id'];
			$ret = $DB->exeSql($sql);
			if ($ret !== false ) $ret = true;
		}
		
		// 清空货架上的对应出售记录
		if ($ret) {
			$ret = $DB->delete('market_user_sale', 'id='.$sale_id);
		}
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'get_coin' => $getCoin,
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('market_undersell', $str);
		}

		return $result;
	}
	
	/**
	 * 获取指定物品的用户销售列表
	 * @param int $uid
	 * @param int $item_id
	 * @param int $quality
	 */
	public static function getUserSaleList($uid, $item_id, $quality)
	{
		global $DB, $L, $G;
		
		$sql = 'SELECT * FROM market_user_sale WHERE item_id='.$item_id.' AND quality='.$quality
				.' ORDER BY price ASC LIMIT 0, 10';
		$list = $DB->getList($sql);
		
		$expire = false;
		$now = time();
//		$mkIdList = array();
		// 处理是否有已过期的销售记录,要隐藏
		foreach ($list as $k=>$v) {
			if ($v['end_time'] < $now) {
//				$mkIdList[] = $v['mk_id'];
				self::handleEndSale($v['uid']);
				unset($list[$k]);
			}
		}
		
		return array(
			'val'	=> true,
			'data'	=> $list
		);
	}
	
	/**
	 * 增加一个货架
	 * @param int $uid
	 */
	public static function addShelf($uid) 
	{
		global $DB, $L, $G;
		
		$cnt = $DB->getCount('market_user_shelf', 'uid='.$uid);
		// 已经达到最大数量的扩展货架
		if ($cnt >= $G['market_max_addon_shelf']) {
			return array(
				'val' => false,
				'msg' => $L['market_add_shelf_reached_max']
			);
		}
		
		$sql = 'SELECT coin,ticket FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);
		
		// 点券不足
		if ($user['ticket'] < $G['market_add_shelf_need_ticket']) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		
		$DB->beginTransaction();
		
		$data = array(
			'uid' => $uid,
		);
		$ret = $DB->insert('market_user_shelf', $data);
		
		// 扣除点券
		if ($ret) {
			$sql = 'UPDATE user set ticket=ticket-'.$G['market_add_shelf_need_ticket'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
			if ($ret !== false) {
				$ret = true;
			}
		}
	
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'used_ticket' => $G['market_add_shelf_need_ticket'],
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('market_add_shelf', $str);
		}
		
		return $result;
	}
	
	/**
	 * 货架物品列表
	 * @param int $uid
	 */
	public static function getShelfList($uid)
	{
		global $DB, $L, $G, $m;
		
		$sql = 'SELECT * FROM market_user_sale WHERE uid='.$uid
				.' ORDER BY sale_time DESC';
		$list = $DB->getList($sql);
		
		$itemList = C('item/item_list');
		
		foreach ($list as $k=>$v) {
			$item = $itemList[$v['item_id']];
			$v['title'] = $item['title'];
			$v['item_type'] = $item['type'];
			$quality = $v['quality'];
			$minPrice = $m->get('marketMinPrice-'.$v['item_id'].'_'.$quality);
			$basePrice = $item['price'][$quality];
			if (!$minPrice) {
				$minPrice = $item['price'][$quality];
			}
			$v['min_price'] = $minPrice;
			$v['base_price'] = $basePrice;
			$list[$k] = $v;
		}
		
		$cnt = $DB->getCount('market_user_shelf', 'uid='.$uid);
		
		return array(
			'val'	=> true,
			'data'	=> array (
				'list' => $list,
				'shelf_count' => $cnt + $G['market_max_sale_group'],
			)
		);
	}
	
	/**
	 * 处理已过期的货架出售记录
	 * @param $uid
	 */
	public static function handleEndSale($uid)
	{
		global $DB, $L, $G, $m;
		
		$now = time();
		
		
		$sql = 'SELECT sale_end_time FROM user WHERE uid='.$uid;
		$saleEndTime = $DB->getValue($sql);
		if (!$saleEndTime || $saleEndTime > $now) {
			return false;
		}
		$sql = 'SELECT * FROM market_user_sale WHERE uid='.$uid.' AND end_time<'.$now;
		$list = $DB->getList($sql);
		// 将所有已过期的记录删除,同时得到金钱
		if (!$list) {
			return false;
		}
		
		$cfgList = C('item/item_list');
		$getCoin = 0;
		$mailListStr = '';
		$ids = '';
		$mkIdList = array();
		foreach ($list as $v) {
			$quality = $v['quality'];
			$qualitySign = $G['id_quality'][$quality];
			$cfg = $cfgList[$v['item_id']];
			$coin = round($v['num'] * ($cfg['price'][$quality]));
			$getCoin += $coin;
			$mailListStr .= sprintf(
									$L['market_auto_sale_mail_record'], 
									$cfg['title'].$qualitySign,
									$v['num'],
									$v['price'],
									$cfg['price'][$quality],
									$coin,
									date('Y-m-d H:i:s', $v['end_time'])
							);
			$ids .= $v['id'].',';
			$mkIdList[] = $v['mk_id'];
			$mkNumModifyList[$v['mk_id']] = $v['num'];
		}
		
		$mailContent = sprintf($L['market_auto_sale_mail_msg'], count($list), $mailListStr);
		
		$DB->beginTransaction();
		
		// 删除过期记录
		$ids = substr($ids, 0, -1);
		$ret = $DB->delete('market_user_sale', 'id in ('.$ids.')');
	
		// 更新对应的市场总数量和最低价
		if ($ret) {
			$updateSql = '';
			foreach ($mkIdList as $mk_id) {
				$sql = 'SELECT MIN(price) FROM  `market_user_sale` WHERE mk_id ='.$mk_id;
				$price = (int)$DB->getValue($sql);
				$minusNum = $mkNumModifyList[$mk_id];
				$updateSql .= 'UPDATE market SET num=num-'.$minusNum.',min_price='.$price.' WHERE mk_id='.$mk_id.';';
			}
			$ret = $DB->exeSql($updateSql);
		}
		
		// 获取金钱并更新最早到期销售的时间
		if ($ret) {
			// 更新玩家的最早结束的销售记录时间
			$sql = 'SELECT min(end_time) FROM market_user_sale WHERE uid='.$uid;
			$newEndTime = (int)$DB->getValue($sql);
			$sql = 'UPDATE user SET coin=coin+'.$getCoin.',sale_end_time='.$newEndTime
					.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		// 发送邮件通知
		if ($ret) {
			$sql = 'SELECT nickname FROM user WHERE uid='.$uid;
			$to_user = $DB->getValue($sql);
			$DB->setTransactionState(false);
			$return = Mail::send(0, $to_user, $mailContent, 1);
			$DB->setTransactionState(true);
		}
		
		if ($ret) {
			$DB->commit();
		} else {
			$DB->rollBack();
		}
		
		return (boolean)$ret;
	}
}










